package com.msx.user.config;


import com.alibaba.fastjson.JSON;
import com.msx.pojo.User;
import com.msx.user.mapper.UserMapper;
import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;

@Service
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Autowired
    private ApplicationContext applicationContext;

    public static Date date = null;
    static {
        try {
            date= DateUtils.parseDate("2020-06-01 00:00:00",
                    "yyyy-MM-dd HH:mm:ss");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }


    @Override
    public String doSharding(Collection availableTargetNames, PreciseShardingValue shardingValue) {
        System.out.println("------------------------------------------");
        System.out.println(JSON.toJSONString("availableTargetNames:"+availableTargetNames));
        System.out.println(JSON.toJSONString("shardingValue:"+shardingValue));
        System.out.println("------------------------------------------");
        //StringBuffer tableName = new StringBuffer();
        //tableName.append(shardingValue.getLogicTableName()).append("_").append(ParaseShardingKeyTool.getYearAndMonth(shardingValue.getValue()));
        //Integer value = (Integer) shardingValue.getValue()%2;
        //String table = "t_user_"+value;
        Long userId = (Long)shardingValue.getValue();
        UserMapper userMapper = applicationContext.getBean(UserMapper.class);
       // textMapper userInfoMapper = applicationContext.getBean(textMapper.class);
        User user = userMapper.selectByPrimaryKey(userId);
        String table = "tb_address_book";
        if(user.getCreateaTime().after(date)){
            table = "tb_address_book_"+ DateFormatUtils.format(user.getCreateaTime(),"yyyy_MM");
        }
        return table;
    }
}
